package cn.tedu.bece.front.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import cn.tedu.bece.front.common.util.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * Mybatis 配置类
 */
@Configuration
@MapperScan("cn.tedu.bece.front.**.mapper")
public class MybatisConfig {

    @Bean
    public MetaObjectHandler fieldFillMetaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                Date now = new Date();
                this.setFieldValByName("createTime", now, metaObject);
                this.setFieldValByName("updateTime", now, metaObject);
                try {
                    String username = SecurityUtils.getUsername();
                    this.setFieldValByName("createBy", username, metaObject);
                    this.setFieldValByName("updateBy", username, metaObject);
                } catch (Exception ignored) {
                    // 没有登录时，获取不到username则忽略
                }
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                this.setFieldValByName("updateTime", new Date(), metaObject);
                try {
                    String username = SecurityUtils.getUsername();
                    this.setFieldValByName("updateBy", username, metaObject);
                } catch (Exception ignored) {
                    // 没有登录时，获取不到username则忽略
                }
            }
        };
    }

}
